//
//  UserAccountViewModel.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/9.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit
class UserAccountVM {
    static let shareUserAccount = UserAccountVM()
    var Account : UserAccont?
    var isExpires : Bool{
        return Account?.expires_Date?.timeIntervalSinceDate(NSDate()) < 0
    }
    var userLogon : Bool {
        return Account?.access_token != nil && !isExpires
    }
    var accessToken : String? {
        if !isExpires{
            return (Account?.access_token)!
        }
        return nil
    }
    /// 头像路径
    var avatarUrl : String{
        return Account?.avatar_large ?? ""
    }
    /// 用户名称
    var screenName : String{
        return Account?.screen_name ?? ""
    }
    var accountpath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    private init(){
        
       Account  =  NSKeyedUnarchiver.unarchiveObjectWithFile((accountpath)) as? UserAccont
        if isExpires {
            Account = nil
        }
        //print("从沙盒获取数据\(Account)")
    }
}
extension UserAccountVM{
    func loadAccessToken(code: String, finished: (isSuccessed: Bool)->()){
    NetworkTools.onceToken.loadAccessToken(code) { (result, error) -> Void in
    if error != nil {
    print(" 出错了 --\(error)")
    
    }
//    print("成功了\(result)")
     self.Account = UserAccont(dict: (result as? [String: AnyObject])!)
    self.loadUserInfo(self.Account!, finished: finished)
    
    }
}

/// 加载用户信息
///
/// - parameter account: 用户模型
    private func loadUserInfo(account: UserAccont,finished: (isSuccessed: Bool)->()){
    NetworkTools.onceToken.loadUserinfo( account.uid!) { (result, error) -> () in
        if error != nil {
            print(error)
            print("loadUserInfo------下载出错")
        }
        guard let _ = result as? [String: AnyObject] else{
            print("格式不正确")
            return
        }
        account.screen_name =  result!["screen_name"] as? String
        account.avatar_large = result!["avatar_large"] as? String
        
        print(account)
         NSKeyedArchiver.archiveRootObject(self.Account!, toFile: self.accountpath)
        finished(isSuccessed: true)
      }
   }
}















